﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;

namespace ZTZP_BEMSS_WPF
{
    public partial class ExcelReader
    {
        public static bool ExportRankingResToExcelFile(string selectedFilePath, Dictionary<BasePriceEntry, Dictionary<string, (int Rank, double Score)>> _RankDic, ObservableCollection<BidQuote> BidQuotes = null)
        {
            // Ensure EPPlus license context is set to NonCommercial
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;

            // Create a new Excel workbook
            using (var package = new ExcelPackage())
            {
                // Add the first worksheet
                var worksheet1 = package.Workbook.Worksheets.Add("评标基准价与公司排名");

                // Set headers for the first worksheet
                worksheet1.Cells[1, 1].Value = "综合参数（下浮率(%), 下浮系数(%), 抽取的B值(万元), 评标基准价(万元)）";
                worksheet1.Cells[1, 2].Value = "评标基准价";  // 单独输出的“评标基准价”
                worksheet1.Cells[1, 3].Value = "公司名称";
                worksheet1.Cells[1, 4].Value = "公司排名";
                worksheet1.Cells[1, 5].Value = "得分";
                worksheet1.Cells[1, 6].Value = "投标报价";  // 新增“投标报价”列
                // 第一行背景色为绿色
                worksheet1.Cells[1, 1, 1, 6].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                worksheet1.Cells[1, 1, 1, 6].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Green);
                // 第一行添加过滤功能
                worksheet1.Cells[1, 1, 1, 6].AutoFilter = true;//自动添加过滤的功能
                // Write data to the first worksheet
                int row = 2;
                foreach (var entry in _RankDic)
                {
                    var basePriceEntry = entry.Key;
                    var companyRankInfo = entry.Value;

                    foreach (var company in companyRankInfo)
                    {
                        var companyName = company.Key;
                        var rank = company.Value.Rank;
                        var score = company.Value.Score;

                        // Find the bid price for the company from BidQuotes
                        var bidPrice = BidQuotes?.FirstOrDefault(b => b.BidCompany == companyName)?.BidPrice ?? 0;

                        // Create a combined string for the "综合参数" column in the desired format
                        string combinedParameters = $"({basePriceEntry.FloatingRate}, {basePriceEntry.FloatingK}, {basePriceEntry.BValue}, {basePriceEntry.BasePrice})";

                        // Write each row of data
                        worksheet1.Cells[row, 1].Value = combinedParameters;  // 合并的“综合参数”
                        worksheet1.Cells[row, 2].Value = basePriceEntry.BasePrice;     // 单独的“评标基准价”
                        worksheet1.Cells[row, 3].Value = companyName;                 // 公司名称
                        worksheet1.Cells[row, 4].Value = rank;                        // 公司排名
                        worksheet1.Cells[row, 5].Value = score;                       // 得分
                        worksheet1.Cells[row, 6].Value = bidPrice;                    // 投标报价

                        row++;  // Move to the next row
                    }
                }

                // Auto fit columns to adjust width
                worksheet1.Cells.AutoFitColumns();

                // Save to file
                try
                {
                    FileInfo fileInfo = new FileInfo(selectedFilePath);
                    package.SaveAs(fileInfo);
                    return true;
                }
                catch (Exception ex)
                {
                    // Handle exceptions (optional)
                    MessageBox.Show($"导出失败：{ex.Message}");
                    return false;
                }
            }
        }


    }

    /// <summary>
    /// SummaryResDialog06.xaml 的交互逻辑
    /// </summary>
    public partial class SummaryResDialog06 : Window
    {
        // 静态字段保存唯一实例
        private static SummaryResDialog06 _instance;
        private RankList _ranklist;//排名信息
        private ObservableCollection<BidQuote> _BidQuotes;//投标报价
        // 私有构造函数，确保只能通过 Instance 获取实例
        private SummaryResDialog06()
        {
            InitializeComponent();
        }

        // 提供对单例实例的访问
        public static SummaryResDialog06 Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new SummaryResDialog06();
                }
                return _instance;
            }
        }

        // 上一步
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 获取 RangeNumDialog05 的单例实例
            RangeNumDialog05 RND05 = RangeNumDialog05.Instance;

            // 如果窗口没有显示，则显示它
            if (!RND05.IsVisible)
            {
                // 计算窗口的位置，使得 CalculationParameters02 的中心在当前窗口的中心
                RND05.Left = this.Left + (this.Width - RND05.Width) / 2;
                RND05.Top = this.Top + (this.Height - RND05.Height) / 2;
                RND05.Show();
            }
            //1
            // 关闭当前窗口
            this.Hide();
        }
        //绘图
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("开发中......");
        }
        //导出Excel
        public void SetRankList(RankList rankList)
        {
            _ranklist = rankList;
        }
        public void SetBidQuotes(ObservableCollection<BidQuote> BidQuotes)
        {
            this._BidQuotes = BidQuotes;
        }
        //导出Excel表格
        private void Button_Click_2(object sender, RoutedEventArgs e)
        { // 选择保存路径和文件名
            string selectedFilePath = ExcelReader.GetFilePathFromSaveDialog("5（导出）-所有基本参数和排名");

            // 如果用户选择了路径，则继续导出
            if (!string.IsNullOrEmpty(selectedFilePath))
            {
                // 导出 Excel 文件
                bool exportSuccess = ExcelReader.ExportRankingResToExcelFile(selectedFilePath, _ranklist._RankDic, _BidQuotes);

                if (exportSuccess)
                {
                    // Ask the user if they want to open the file
                    var result = MessageBox.Show("导出成功！是否立即打开文件？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.Yes)
                    {
                        // Open the Excel file
                        Process.Start(new ProcessStartInfo(selectedFilePath) { UseShellExecute = true });
                    }
                }
                else
                {
                    MessageBox.Show("文件导出失败");
                }
            }
            else
            {
                MessageBox.Show("未选择导出Excel文件");
            }
           

        }
    }
}
